import React,{useState,useEffect} from 'react'
 import "./SideMenu.css";//5.引入css要放在上边
import {withRouter} from 'react-router-dom'
import { Layout, Menu } from 'antd';
import {
    UserOutlined
  } from '@ant-design/icons';
import axios from 'axios'
import {connect}  from "react-redux";

const { Sider } = Layout;
const { SubMenu } = Menu;
/**
 * 使用 _embed 对rights表和children表进行关联，得到侧边栏数据
 * 使用映射表，渲染图标
 */

 const iconList = {
  "/home":<UserOutlined />,
  "/user-manage":<UserOutlined />,
  "/user-manage/list":<UserOutlined />,
  "/right-manage":<UserOutlined />,
  "/right-manage/role/list":<UserOutlined />,
  "/right-manage/right/list":<UserOutlined />
  //.......
}

function SideMenu(props) {
  const [menu, setMenu] = useState([]);
  const {role:{rights}}=JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    axios.get('http://localhost:5000/rights?_embed=children').then(
      res=>{setMenu(res.data);}
    )
  }, [])
  const checkPermission=(item)=>{
    // 如果该user的rights中没有该项，就不显示。
    return item.pagepermisson===1&&rights.includes(item.key)//includes数组方法？
  } 

  const renderMenu=(menuList)=>{      
    return menuList.map(item=>{
      if(item.children?.length>0&&checkPermission(item)){
        return <SubMenu key={item.key}  title={item.title} icon={iconList[item.key]}>
                    {renderMenu(item.children)}
        </SubMenu>
      }
      else
          return checkPermission(item)&&<Menu.Item key={item.key} icon={iconList[item.key]} onClick={()=>props.history.push(item.key)}>
            {item.title}
            </Menu.Item>
    })
 }

    
    const selectedKeys= [props.location.pathname]
    const open = "/"+props.location.pathname.split("/")[1];
    return (
        <Sider trigger={null} collapsible collapsed={props.isCollapsed} >
          <div style={{display:"flex",height:"100%","flexDirection":"column"}}>
            <div className="logo">全球新闻发布系统</div>
            <div style={{flex:1,"overflow":"auto"}}>
            <Menu theme="dark" mode="inline" selectedKeys={selectedKeys} defaultOpenKeys={[open]} >
            {renderMenu(menu)}
            </Menu> 
            </div>
          </div>
          
        </Sider>
     )
 }

 const mapStateToProps=(state)=>{ //返回值为props
     const {collApsed:{isCollapsed}}=state
     return{
         isCollapsed
     }
 }
 export default connect(mapStateToProps)(withRouter(SideMenu))
